#ifndef BASE_SERIAL_H
#define BASE_SERIAL_H

#include <string>
#include <thread>
#include <atomic>
#include <chrono>
#include <ctime>
#include <unistd.h>
#include <cstdint>
#include <vector>
#include <memory>

struct ReceivedData {
    double yaw;
    double pitch;
    double roll;
    std::chrono::steady_clock::time_point timestamp;
};

#pragma pack(push, 1)
struct ReceivePacket {
    uint8_t header=0xAA;
    uint8_t mode;
    float yaw;
    float pitch;
    float roll;
    uint8_t tail=0X5A;
};

struct SendPacket {
    uint8_t header=0XBB;
    float yaw;
    float pitch;
    float distance;
    uint8_t fire_advice;
    uint8_t check;
    uint8_t tail=0X5B;
};
#pragma pack(pop)

class Serial {
public:
    Serial();
    ~Serial();

    bool init(const std::string& config_path);
    void close();

    bool readData(ReceivedData& data);
    bool sendData(const SendPacket& data);

    bool isVirtual() const { return virtual_serial_; }
    bool isOpen() const { return fd_ != -1; }

private:
    std::string port_;
    int baudrate_;
    std::string flow_control_;
    std::string parity_;
    std::string stop_bits_;
    bool virtual_serial_;

    // 虚拟串口使用的默认值
    ReceivedData virtual_data_;

    // 实际串口文件描述符
    int fd_;

    bool openPort();
    void closePort();
    bool readFromPort(std::vector<uint8_t>& buffer, size_t size);
    bool writeToPort(const std::vector<uint8_t>& data);

    // 断线重连机制
    bool reopenPort();
};

#endif //BASE_SERIAL_H
